package com.mfw.springboot.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mfw.springboot.common.DataGroupByDateDTO;
import com.mfw.springboot.common.ErrorCode;
import com.mfw.springboot.constant.CommonConstant;
import com.mfw.springboot.exception.ThrowUtils;
import com.mfw.springboot.mapper.UserClassRelationMapper;
import com.mfw.springboot.model.dto.userClassRelation.UserClassRelationQueryRequest;
import com.mfw.springboot.model.entity.ClassInfo;
import com.mfw.springboot.model.entity.User;
import com.mfw.springboot.model.entity.UserClassRelation;
import com.mfw.springboot.model.vo.ClassInfoVO;
import com.mfw.springboot.model.vo.UserClassRelationVO;
import com.mfw.springboot.model.vo.UserVO;
import com.mfw.springboot.service.ClassInfoService;
import com.mfw.springboot.service.UserClassRelationService;
import com.mfw.springboot.service.UserService;
import com.mfw.springboot.utils.DateUtils;
import com.mfw.springboot.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户班级关系服务实现
 *
 * @author mfw
 * @from <a href="https://gitee.com/hanhuaifei/projects">我的gitee</a>
 * @Date 2024/9/26
 */
@Service
@Slf4j
public class UserClassRelationServiceImpl extends ServiceImpl<UserClassRelationMapper, UserClassRelation> implements UserClassRelationService {

    @Resource
    private UserService userService;

    @Resource
    private ClassInfoService classInfoService;

    /**
     * 校验数据
     *
     * @param userClassRelation
     * @param add               对创建的数据进行校验
     */
    @Override
    public void validUserClassRelation(UserClassRelation userClassRelation, boolean add) {
        ThrowUtils.throwIf(userClassRelation == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long userId = userClassRelation.getUserId();
        Long classId = userClassRelation.getClassId();


        // 创建数据时，参数不能为空
        if (add) {
            // 补充校验规则
            ThrowUtils.throwIf(userId == null || userId < 0, ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(classId == null || classId < 0, ErrorCode.PARAMS_ERROR);
        }

    }

    /**
     * 获取查询条件
     *
     * @param userClassRelationQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<UserClassRelation> getQueryWrapper(UserClassRelationQueryRequest userClassRelationQueryRequest) {
        QueryWrapper<UserClassRelation> queryWrapper = new QueryWrapper<>();
        if (userClassRelationQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = userClassRelationQueryRequest.getId();
        Long userId = userClassRelationQueryRequest.getUserId();
        Long classId = userClassRelationQueryRequest.getClassId();
        String role = userClassRelationQueryRequest.getRole();
        String status = userClassRelationQueryRequest.getStatus();
        String sortField = userClassRelationQueryRequest.getSortField();
        String sortOrder = userClassRelationQueryRequest.getSortOrder();
        // 补充需要的查询条件
        // 精确查询
        queryWrapper.ne(ObjectUtils.isNotEmpty(classId), "class_id", classId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "user_id", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(role), "role", role);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), "status", status);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取用户班级关系封装
     *
     * @param userClassRelation
     * @param request
     * @return
     */
    @Override
    public UserClassRelationVO getUserClassRelationVO(UserClassRelation userClassRelation, HttpServletRequest request) {
        // 对象转封装类
        UserClassRelationVO userClassRelationVO = UserClassRelationVO.objToVo(userClassRelation);

        // 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = userClassRelation.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        userClassRelationVO.setUser(userVO);

        // 2. 关联查询班级信息
        Long classId = userClassRelation.getClassId();
        ClassInfo classInfo = null;
        if (classId != null && classId > 0) {
            classInfo = classInfoService.getById(classId);
        }
        ClassInfoVO classInfoVO = classInfoService.getClassInfoVO(classInfo, request);
        userClassRelationVO.setClassInfo(classInfoVO);

        return userClassRelationVO;
    }

    /**
     * 分页获取用户班级关系封装
     *
     * @param userClassRelationPage
     * @param request
     * @return
     */
    @Override
    public Page<UserClassRelationVO> getUserClassRelationVOPage(Page<UserClassRelation> userClassRelationPage, HttpServletRequest request) {
        List<UserClassRelation> userClassRelationList = userClassRelationPage.getRecords();
        Page<UserClassRelationVO> userClassRelationVOPage = new Page<>(userClassRelationPage.getCurrent(), userClassRelationPage.getSize(), userClassRelationPage.getTotal());
        if (CollUtil.isEmpty(userClassRelationList)) {
            return userClassRelationVOPage;
        }
        // 对象列表 => 封装对象列表
        List<UserClassRelationVO> userClassRelationVOList = userClassRelationList.stream().map(userClassRelation -> {
            return UserClassRelationVO.objToVo(userClassRelation);
        }).collect(Collectors.toList());

        // 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = userClassRelationList.stream().map(UserClassRelation::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 关联查询班级信息
        Set<Long> classIdSet = userClassRelationList.stream().map(UserClassRelation::getClassId).collect(Collectors.toSet());
        Map<Long, List<ClassInfo>> classIdClassInfoListMap = classInfoService.listByIds(classIdSet).stream()
                .collect(Collectors.groupingBy(ClassInfo::getId));
        // 填充信息
        userClassRelationVOList.forEach(userClassRelationVO -> {
            //用户
            Long userId = userClassRelationVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            userClassRelationVO.setUser(userService.getUserVO(user));
            //班级
            Long classId = userClassRelationVO.getClassId();
            ClassInfo classInfo = null;
            if (classIdClassInfoListMap.containsKey(classId)) {
                classInfo = classIdClassInfoListMap.get(classId).get(0);
            }
            userClassRelationVO.setClassInfo(classInfoService.getClassInfoVO(classInfo, request));

        });
        // endregion

        userClassRelationVOPage.setRecords(userClassRelationVOList);
        return userClassRelationVOPage;
    }

    /**
     * 分按日期分组查询用户班级关系新增数量
     *
     * @param beginDate 开始时间
     * @param endDate   结束时间
     * @return
     */
    @Override
    public List<DataGroupByDateDTO> countByDay(Date beginDate, Date endDate) {
        QueryWrapper<UserClassRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DATE_FORMAT(create_time, '%Y-%m-%d') AS day", "COUNT(1) AS num");
        queryWrapper.ge("create_time", beginDate);
        queryWrapper.le("create_time", endDate);
        queryWrapper.groupBy("day");
        queryWrapper.orderByAsc("day");
        // 执行查询
        List<Map<String, Object>> results = this.baseMapper.selectMaps(queryWrapper);
        // 映射到 DataGroupByDateDTO
        return results.stream().map(result -> {
            DataGroupByDateDTO dto = new DataGroupByDateDTO();
            dto.setDay(DateUtils.parse(result.get("day").toString(), DateUtils.FMT_YMD));
            dto.setNum((Long) result.get("num"));
            return dto;
        }).collect(Collectors.toList());
    }

}
